 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.rca.entity.SwCkStatementJtyktSubwayconsume;
import com.zdkj.subway.rca.entity.SwCkStatementJtyktSubwayconsumeTmp;
import com.zdkj.subway.rca.mapper.SwCkStatementJtyktSubwayconsumeTmpMapper;
import com.zdkj.subway.rca.service.SwCkStatementJtyktSubwayconsumeService;
import com.zdkj.subway.rca.service.SwCkStatementJtyktSubwayconsumeTmpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.ZoneId;
import java.util.*;

/**
 * 交通一卡通地铁消费对账确认临时表
 *
 * @author stw
 * @date 2020-10-24 22:07:34
 */
@Service
public class SwCkStatementJtyktSubwayconsumeTmpServiceImpl extends ServiceImpl<SwCkStatementJtyktSubwayconsumeTmpMapper, SwCkStatementJtyktSubwayconsumeTmp> implements SwCkStatementJtyktSubwayconsumeTmpService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwCkStatementCatSubwayconsumeTmpServiceImpl.class);
    private String parsePattern = "yyyy.MM.dd";
    @Autowired
    private SwCkStatementJtyktSubwayconsumeService swCkStatementJtyktSubwayconsumeService;

    @Override
    public Boolean saveBatchWithExcel(final File excelFile) throws Exception {
        List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(4).doReadSync();
        if (CollectionUtil.isNotEmpty(listMap)) {
            List<SwCkStatementJtyktSubwayconsumeTmp> listDb = new ArrayList<>();
            MultipartFileToFile.delteTempFile(excelFile);
            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 表示所在的列 和所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

                SwCkStatementJtyktSubwayconsumeTmp tmpObj = new SwCkStatementJtyktSubwayconsumeTmp();
                tmpObj.setTradeDateTmp(data.get(0));//交易日期

                tmpObj.setTicketExtensionAmountTmp(data.get(1));
                tmpObj.setTicketExtensionMoneyTmp(data.get(2));
                tmpObj.setOutboundAmountTmp(data.get(3));
                tmpObj.setOutboundMoneyTmp(data.get(4));

                tmpObj.setPullinAmountTmp(data.get(5));
                tmpObj.setPullinMoneyTmp(data.get(6));
                tmpObj.setTotalAmountTmp(data.get(7));
                tmpObj.setTotalMoneyTmp(data.get(8));

                if (StringUtils.isEmpty(tmpObj.getTradeDateTmp())
                        || StringUtils.isEmpty(tmpObj.getTotalAmountTmp())
                        || StringUtils.isEmpty(tmpObj.getTotalMoneyTmp())
                        ) {
                    continue;
                }
                if (!parseDate(tmpObj.getTradeDateTmp())) {
                    continue;
                }

                final SwCkStatementJtyktSubwayconsumeTmp obj = ObjectUtils.getDefaultObj(SwCkStatementJtyktSubwayconsumeTmp.class);
                BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
                checkErr(obj);
                listDb.add(obj);

            }
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("CREATOR_ID", listDb.get(0).getCreatorId());
            this.baseMapper.deleteByMap(columnMap);
            return this.saveBatch(listDb);

        }

        return false;
    }

    private void checkErr(SwCkStatementJtyktSubwayconsumeTmp obj) {
        //更新字段
        String tradeDateTmp = obj.getTradeDateTmp();
        try {
            Date tradeDate = DateUtils.parseDate(tradeDateTmp, parsePattern);
            obj.setTradeDate(tradeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        } catch (Exception e) {
            obj.setErrMsg("交易日期 为空或格式错误");
        }

        try {
            String ticketExtensionAmountTmp = obj.getTicketExtensionAmountTmp();
            Long ticketExtensionAmount = Long.parseLong(ticketExtensionAmountTmp);
            obj.setTicketExtensionAmount(ticketExtensionAmount);

            String outboundAmountTmp = obj.getOutboundAmountTmp();
            Long outboundAmount = Long.parseLong(outboundAmountTmp);
            obj.setOutboundAmount(outboundAmount);

            String pullinAmountTmp = obj.getPullinAmountTmp();
            Long pullinAmount = Long.parseLong(pullinAmountTmp);
            obj.setPullinAmount(pullinAmount);

            String totalAmountTmp = obj.getTotalAmountTmp();
            Long totalAmount = Long.parseLong(totalAmountTmp);
            obj.setTotalAmount(totalAmount);
        } catch (Exception e) {
            obj.setErrMsg("笔数 为空或格式错误");
        }

        try {
            BigDecimal num = new BigDecimal("100");

            String ticketExtensionMoneyTmp = obj.getTicketExtensionMoneyTmp();
            BigDecimal ticketExtensionMoney = new BigDecimal(ticketExtensionMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            ticketExtensionMoney = ticketExtensionMoney.multiply(num);
            obj.setTicketExtensionMoney(ticketExtensionMoney.longValue());

            String outboundMoneyTmp = obj.getOutboundMoneyTmp();
            BigDecimal outboundMoney = new BigDecimal(outboundMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            outboundMoney = outboundMoney.multiply(num);
            obj.setOutboundMoney(outboundMoney.longValue());

            String pullinMoneyTmp = obj.getPullinMoneyTmp();
            BigDecimal pullinMoney = new BigDecimal(pullinMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            pullinMoney = pullinMoney.multiply(num);
            obj.setPullinMoney(pullinMoney.longValue());

            String totalMoneyTmp = obj.getTotalMoneyTmp();
            BigDecimal totalMoney = new BigDecimal(totalMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            totalMoney = totalMoney.multiply(num);
            obj.setTotalMoney(totalMoney.longValue());
        } catch (Exception e) {
            obj.setErrMsg("金额 为空或格式错误");
        }


        //判断数据是否存在
        SwCkStatementJtyktSubwayconsume SwCkStatementJtyktSubwayconsume = new SwCkStatementJtyktSubwayconsume();
        BeanUtils.copyProperties(obj, SwCkStatementJtyktSubwayconsume, "deptId","creatorId","creatorName","createTime");
        List<SwCkStatementJtyktSubwayconsume> list = swCkStatementJtyktSubwayconsumeService.list(Wrappers.query(SwCkStatementJtyktSubwayconsume));
        if (list != null && !list.isEmpty()) {
            obj.setErrMsg("数据已存在");
        }
    }

    private boolean parseDate(String string) {
        boolean convertSuccess = true;
        if (string == null) {
            return false;
        }

        try {
            DateUtils.parseDate(string, parsePattern);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }

    @Override
    public void saveBatchWithExcelOk(Integer creatorId) {
        //导入先删除
        this.baseMapper.deleteBatchWithExcelOk(creatorId);
        //导入先删除再添加包括重复的
        this.baseMapper.saveBatchWithExcelOkRepeat(creatorId);
        //this.baseMapper.saveBatchWithExcelOk(creatorId);
        saveBatchWithExcelCancel(creatorId);
    }

    @Override
    public void saveBatchWithExcelCancel(Integer creatorId) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("CREATOR_ID", creatorId);
        this.baseMapper.deleteByMap(columnMap);
    }
}
